package com.ee.chat.api.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ee.chat.api.common.CommonService;
import com.ee.chat.common.dao.HostCallLogMapper;
import com.ee.chat.common.dao.PayChannelConfigMapper;
import com.ee.chat.common.dao.UserOperationLogMapper;
import com.ee.chat.common.entity.HostCallLog;
import com.ee.chat.common.entity.PayChannelConfig;
import com.ee.chat.common.entity.UserOperationLog;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * 清理数据任务类
 */
@Component
public class ClearDataTask {
    private Logger log = LoggerFactory.getLogger(ClearDataTask.class);

    @Resource
    CommonService commonService;
    @Resource
    PayChannelConfigMapper payChannelConfigMapper;
    @Resource
    UserOperationLogMapper userOperationLogMapper;
    @Resource
    HostCallLogMapper hostCallLogMapper;

    /**
     * 重置支付渠道，零点30执行
     */
    @Scheduled(cron = "0 30 0 * * ?")
    public void resetPayConfig(){
        if(!commonService.getIpStatus()){
            return;
        }

        log.info("重置支付渠道开始");
        List<PayChannelConfig> configs = payChannelConfigMapper.selectByStatus(2);  //获取临时无效的渠道
        for(PayChannelConfig config : configs){
            config.setStatus(0);

            payChannelConfigMapper.updateById(config);
        }
        log.info("重置支付渠道结束");
    }

    /**
     * 清理无用的用户操作数据和主播点赞记录，12点执行
     */
    @Scheduled(cron = "0 0 12 * * ?")
    public void cleanOperationData(){
        if(!commonService.getIpStatus()){
            return;
        }

        log.info("清理无用数据开始");

        LocalDateTime localDateTime = LocalDateTime.now();
        localDateTime = localDateTime.plusDays(-1);
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

        //删除多余的用户操作数据
        QueryWrapper<UserOperationLog> wrapper = new QueryWrapper<>();
        wrapper.lt("create_time", date);
        userOperationLogMapper.delete(wrapper);

        //删除多余的主播打招呼数据
        QueryWrapper<HostCallLog> wrapper1 = new QueryWrapper<>();
        wrapper.lt("create_time", date);
        hostCallLogMapper.delete(wrapper1);

        log.info("清理无用数据结束");
    }
}
